package com.school_admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.school_admin.config.JwtUtil;
import com.school_admin.config.Result;
import com.school_admin.entity.Admin;
import com.school_admin.entity.User;
import com.school_admin.mapper.AdminMapper;
import com.school_admin.service.impl.AdminServiceImpl;
import com.school_admin.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    private final AdminServiceImpl adminService;
    private final UserServiceImpl userService;
    private final AdminMapper adminMapper;
    private final JwtUtil jwtUtil;

    @Autowired
    public AdminController(AdminServiceImpl adminService, UserServiceImpl userService, AdminMapper adminMapper, JwtUtil jwtUtil) {
        this.adminService = adminService;
        this.userService = userService;
        this.adminMapper = adminMapper;
        this.jwtUtil = jwtUtil;
    }
    // TODO 管理员登录
    @PostMapping("login")
    public Result<Map<String,Object>> login(Admin admin){
        // 判断登录
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername, admin.getUsername());
        Admin adminOne = adminService.getOne(wrapper);
        if (adminOne == null || !adminOne.getPassword().equals(admin.getPassword())) {
            return Result.fail("用户名或密码错误");
        }
        // 返回登录结果
        // 生成token
        String token = jwtUtil.createToken(adminOne);
        Map<String, Object> map = new HashMap<>();
        map.put("user",adminOne);
        map.put("token",token);
        return Result.success(map,"登录成功");
    }
    // TODO 修改密码
    @PutMapping("updatePassword")
    public Result<String> updatePassword(User user){
        boolean is = userService.updateById(user);
        if (is) {
            return Result.success("密码修改成功");
        } else {
            return Result.fail("密码修改失败");
        }
    }
}
